--------------------------------------------------------------------------------
--------------------------------------------------------------------------------

--local modOptions
--if (Spring.GetModOptions) then
--  modOptions = Spring.GetModOptions()
--end

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Utility
--

-- local function tobool(val)
  -- local t = type(val)
  -- if (t == 'nil') then
    -- return false
  -- elseif (t == 'boolean') then
    -- return val
  -- elseif (t == 'number') then
    -- return (val ~= 0)
  -- elseif (t == 'string') then
    -- return ((val ~= '0') and (val ~= 'false'))
  -- end
  -- return false
-- end

local function isTable(x)  return (type(x) == 'table')   end

local WeaponDefs = DEFS.weaponDefs  --needed

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------

--VFS.Include("luarules/utils/debug.lua")
--for tableName, ud in pairs(UnitDefs) do printTable ("UnitDefs["..tableName.."]", ud) end 

-- fix CustomParams
for udName, ud in pairs(UnitDefs) do
  if (isTable(ud)) then
    ud.customparams = ud.customparams or {}
  else
    Spring.Echo('[unitdefs_post.lua] Error: Invalid unitDef: UnitDefs['..udName..']')
    UnitDefs[udName] = nil
  end      
end

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------

VFS.Include("gamedata/soundcategories.lua")

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------

-- Wreckages
function GenerateUnitWrecks (ud)
  local params = ud.customparams

  local wrecks = params.wreckModels
  local heaps = params.heapModels
  params.wreckModels = nil
  params.heapModels = nil
  if (not isTable(wrecks)) then wrecks = { wrecks } end
  if (not isTable(heaps)) then heaps  = { heaps  } end
  local numWrecks = #wrecks
  local numHeaps = #heaps
  local numTotal = numWrecks + numHeaps
    
  if (numTotal <= 0) then return end
    
  if (not isTable(ud.featureDefs)) then ud.featureDefs = {} end
  local fds = ud.featureDefs
    
  numTotal = numTotal + 1
  local maxDamage = ud.maxDamage or 1.0
  local metalCost = ud.buildCostMetal or 0.0
  local lastWreckName = nil
  local wreckName
    
  for i = numHeaps, 1, -1 do
    wreckName = (numHeaps > 1) and ("HEAP" .. i) or "HEAP"
      
    fds[wreckName] = {
      description      = "Debris - " .. ud.name,
      world            = "All Worlds",
      category         = "heaps",	  	  
      object           = heaps[i],
	
      footprintX       = ud.footprintX,
      footprintZ       = ud.footprintZ,
      --height           = 4,  --?
      blocking         = false,	
        
      damage           = maxDamage * 0.6,	  
      metal            = metalCost * (1 - (numWrecks + i) / numTotal),
      energy           = 0,	  
      --reclaimTime      = 50,
      reclaimable      = true,	  

      featureDead      = lastWreckName,        
      featurereclamate = "SMUDGE01",
      seqnamereclamate = "TREE1RECLAMATE",
    }  
      
    lastWreckName = wreckName
  end
    
  for i = numWrecks, 1, -1 do
    wreckName = (numWrecks > 1) and ("WRECK" .. i) or "WRECK"
      
    fds[wreckName] = {
      description      = "Wreckage - " .. ud.name,
      world            = "All Worlds",
      category         = "corpses",	  	  
      object           = wrecks[i],
	
      footprintX       = ud.footprintX,
      footprintZ       = ud.footprintZ,
      --height           = 20,  --?
      blocking         = not ud.floater,  --true,	--waterline 	  
      damage           = maxDamage * 0.6,  
      metal            = metalCost * (1 - i / numTotal),
      energy           = 0,	  
      --reclaimTime      = 150,
      reclaimable      = true,	  

      featureDead      = lastWreckName,
      featurereclamate = "SMUDGE01",
      seqnamereclamate = "TREE1RECLAMATE",
      --smokeTime        = 300,
      --mass = (fd->metal * 0.4f) + (fd->maxHealth * 0.1f)
      --hitdensity ? 

      collisionVolumeType    = ud.collisionVolumeType,
      collisionVolumeTest    = ud.collisionVolumeTest, 
      collisionVolumeOffsets = ud.collisionVolumeOffsets,  
      collisionVolumeScales  = ud.collisionVolumeScale, --TODO: units with multiple colvols?
    }  
      
    lastWreckName = wreckName
  end 

  ud.corpse = ud.corpse or lastWreckName
end

for _, ud in pairs(UnitDefs) do
  GenerateUnitWrecks(ud)
end


--------------------------------------------------------------------------------
-- Collision Volumes
local colVolTypes = {
  ellipsoid = 0,
  cylinder  = 1,
  cylinderx = 1,
  cylindery = 1,
  cylinderz = 1,  
  box       = 2,
  sphere    = 3,
  footprint = 4,
}

local colVolAxes = {
  cylinderx = 0,
  cylindery = 1,
  cylinderz = 2, 
}  

for _, ud in pairs(UnitDefs) do
  local params = ud.customparams
  local hasColVols = false  --TODO: turret col vols
  
  if (isTable(params.collisionvolumes)) then
    for _, cv in pairs(params.collisionvolumes) do
      if (isTable(cv)) then
        cv.scale  = cv.scale  or cv[1]
        cv.offset = cv.offset or cv[2]
        cv.type   = cv.type   or cv[3]
        cv[1] = nil
        cv[2] = nil
        cv[3] = nil      
        hasColVols = true
        
        if (type(cv.type) == "string") then
          cv.axis = colVolAxes[cv.type]
          cv.type = colVolTypes[cv.type]
        end
        cv.type = cv.type or colVolTypes["box"]
        cv.axis = cv.axis or 2
      end
    end
  end
  ud.usePieceCollisionVolumes = hasColVols
  params.usePieceCollisionVolumes = hasColVols and true or nil
  
  --remove params that are temporary and shouldn't be loaded
  -- params.soundcategory = nil
  params.wreckmodels = nil
  params.heapmodels = nil
end

  
-- customParams = {
  -- wreckModels = { "c_heavytank_wreck1.s3o", "c_heavytank_wreck1.s3o" },  --"c_heavytank_wreck1.s3o", "c_heavytank_wreck2.s3o"
  -- heapModels = { "3x3d.3do" },
  
  -- constructionWireframe = 10.0,
  -- scaffoldingBoxes = {
    -- { -10, 0, -10, 10, 20, 10 },
  -- },
    
  -- soundCategory = "VEHICLE1",
  
  -- armorThickness = 100,
	
  -- lightDamageChance = 0.2,	
  -- mediumDamageChance = 0.4,
  -- heavyDamageChance = 0.4,
  
  -- collisionVolumes = {
    -- hull = { 
      -- scale = {29, 15, 174},
      -- offset = {0, 1.5, -8},
      -- type = "cylindery",
    -- },
    -- hull     = { {29, 15, 174}, {0, 1.5, -8}, "cylindery" },
  -- },
  
  -- rangeCircles = {
    -- [1000] = "ARTY",
  -- },
-- },
  

--------------------------------------------------------------------------------
-- Set reverse velocities
-- (only ships and tanks)

for _, ud in pairs(UnitDefs) do
  --if ((not ud.tedclass) or ud.tedclass:find("SHIP",1,true) or ud.tedclass:find("TANK",1,true)) then
  if (not ud.yardmap and ud.maxvelocity and not ud.canfly) then
    ud.maxreversevelocity = tonumber(ud.maxvelocity) * (tonumber(ud.maxreversevelocity) or 0.5)
  end
end 

--------------------------------------------------------------------------------
-- Set proper turnInPlaceSpeedLimit

for _, ud in pairs(UnitDefs) do
  if (ud.turninplace == false) then
    ud.turninplacespeedlimit = tonumber(ud.maxvelocity) * 0.5
  end
end

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------

--
-- Set unit faction and build options
--
--[[
local function TagTree(unit, faction)
  local morphDefs = VFS.Include"LuaRules/Configs/morph_defs.lua"
  
  local function Tag(unit)
  	local ud = UnitDefs[unit]
    if (not ud or ud.faction) then
      return
    end
    ud.faction = faction
    if (UnitDefs[unit].buildoptions) then
	  for _, buildoption in ipairs(ud.buildoptions) do
        Tag(buildoption)
      end
    end
	
    if (morphDefs[unit]) then
      if (morphDefs[unit].into) then
        Tag(morphDefs[unit].into)
      else
        for _, t in ipairs(morphDefs[unit]) do
          Tag(t.into)
        end
      end        
    end
  end
  
  Tag(unit)
end

for _, side in ipairs(sideData) do
  TagTree(side.startunit, side.name)
end
--TagTree("c_factory", "Cannons")
--TagTree("m_factory", "Missiles")
]]--
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- 3dbuildrange for all none plane builders
--[[
for _, ud in pairs(UnitDefs) do
  if (tobool(ud.builder) and not tobool(ud.canfly)) then
    ud.buildrange3d = true
  end
end
--]]

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Disable smoothmesh
--[[
for _, ud in pairs(UnitDefs) do
    if (ud.canfly) then ud.usesmoothmesh = false end
end 
--]]
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Lasercannons going through units fix
-- 
--[[
for _, ud in pairs(UnitDefs) do
  ud.collisionVolumeTest = 1
end
--]]
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--  No leveling ground
--[[
for _, ud in pairs(UnitDefs) do
  if (ud.yardmap)  then
    ud.levelGround = false
  end
end
--]]
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- No reclaiming of live units
-- 
--[[
for _, ud in pairs(UnitDefs) do
  ud.reclaimable = false
end
--]]
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Remove Restore
-- 
--[[
for _, ud in pairs(UnitDefs) do
  if tobool(ud.builder) then
	ud.canRestore = false
  end
end
--]]
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------